package com.heima.homeservicemanagementsystem.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.Operator;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.homeservicemanagementsystem.config.annotation.RestControllerMapping;
import com.heima.homeservicemanagementsystem.entity.ServiceClassification;
import com.heima.homeservicemanagementsystem.entity.Servicedetails;
import com.heima.homeservicemanagementsystem.mapper.ServiceClassificationMapper;
import com.heima.homeservicemanagementsystem.module.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author jcf
 * @Date 2025/4/18
 */
@Slf4j
@Tag(name = "es相关的搜索")
@RestControllerMapping("/es")
@SaIgnore
public class SearchserviceController {

    @Autowired
    private ElasticsearchClient client;
    @Autowired
    private ServiceClassificationMapper serviceClassificationMapper;

    @PostMapping("/search")
    @Operation(summary = "es相关的搜索")
    public Result<ArrayList<Servicedetails>> search(@RequestParam String name) throws IOException {
        log.info("es相关的搜索：{}", name);
        SearchResponse<Map> searchResponse = client.search(srBuilder -> srBuilder
                        .index("servicedetails")
                        .query(queryBuilder -> queryBuilder
                                .multiMatch(multiMatchQueryBuilder -> multiMatchQueryBuilder
                                        .fields("serviceName", "remark")
                                        .query(name)
                                        .operator(Operator.Or)
                                )
                        )
                        .highlight(highlightBuilder -> highlightBuilder
                                .preTags("<font style='color:red'>")
                                .postTags("</font>")
                                .requireFieldMatch(false)
                                .fields("serviceName", highlightFieldBuilder -> highlightFieldBuilder)
                                .fields("remark", highlightFieldBuilder -> highlightFieldBuilder)
                        )
                        .sort(s -> s.field(ss -> ss.field("id.keyword").order(SortOrder.Asc)))
                , Map.class
        );

        //解析查询结果
        System.out.println(searchResponse);
        HitsMetadata<Map> hits = searchResponse.hits();
        List<Hit<Map>> hitList = searchResponse.hits().hits();
        ArrayList<Servicedetails> objects = new ArrayList<>();
        for (Hit<Map> mapHit : hitList) {
            Map<String, List<String>> highlights = mapHit.highlight();
            Servicedetails servicedetails = new ObjectMapper().convertValue(mapHit.source(), Servicedetails.class);

            // 处理高亮信息
            if (highlights.containsKey("remark")) {
                servicedetails.setRemark(highlights.get("remark").get(0));
            }
            if (highlights.containsKey("serviceName")) {
                servicedetails.setServiceName(highlights.get("serviceName").get(0));
            }

//            System.out.println("servicedetails: " + servicedetails);
            objects.add(servicedetails);
        }
        return Result.success(objects);
    }

    /**
     * 搜索推荐
     *
     * @return com.heima.homeservicemanagementsystem.module.Result
     * @author jinchengfei
     * @create 2025/4/20
     **/

    @GetMapping("/searchRecommend")
    public Result searchRecommend() {
        List<ServiceClassification> serviceClassifications = serviceClassificationMapper.selectList(
                new LambdaQueryWrapper<ServiceClassification>().eq(ServiceClassification::getType, 1)
                        .last("ORDER BY RAND() LIMIT 9")

        );
        log.info("总数：{}", serviceClassifications);


        return Result.success(serviceClassifications);
    }

    @GetMapping("/hot")
    public Result searchHot() {
        List<ServiceClassification> serviceClassifications = serviceClassificationMapper.selectList(
                new LambdaQueryWrapper<ServiceClassification>().eq(ServiceClassification::getType, 1)
                        .last("ORDER BY RAND() LIMIT 7")

        );
        log.info("总数：{}", serviceClassifications);


        return Result.success(serviceClassifications);
    }

}
